"use client";
import type { FC } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import {
  useContentStore,
  useCustomizationStore,
  usePersonalDetailsStore,
  useStore,
} from "../../../store";
import { Component } from "@/cvcomponents";

const Index: FC<any> = ({ leftPart }) => {
  const ref = useRef<HTMLDivElement>(null);
  const ref2 = useRef<HTMLDivElement>(null);
  const a4Width = 820;
  const a4Height = 1159.71;
  const [scale, setScale] = useState(0);
  const [show, setShow] = useState(false);
  const scaleRef = useRef(0);
  const pageNumRef = useRef(1);
  const { content } = useContentStore();
  const { customization } = useCustomizationStore();
  const { personalDetails } = usePersonalDetailsStore();
  const { setHtml, fontScale } = useStore();
  const getScale = () => {
    const r = 1.04;
    let scale = 1;
    if (window.innerWidth <= 800) {
      scale = window.innerWidth / a4Width / r;
    } else {
      scale = (window.innerWidth - leftPart.current.offsetWidth) / a4Width / r;
    }
    return scale;
  };
  const setPreviewSize = () => {
    if (ref.current) {
      const scale = getScale();
      scaleRef.current = scale;
      setScale(scale);
      (ref.current as any).style.width = `${a4Width * scale}px`;
      (ref.current as any).style.height = `${
        (pageNumRef.current * a4Height + (pageNumRef.current - 1) * 10) *
        (scale || scaleRef.current)
      }px`;
    }
  };
  useLayoutEffect(() => {
    setShow(true);
    setPreviewSize();
  }, []);
  useEffect(() => {
    const resize = () => {
      setPreviewSize();
    };
    window.addEventListener("resize", resize);
    return () => {
      window.removeEventListener("resize", resize);
    };
  }, []);
  const onChange = (html) => {
    setHtml(html);
  };
  const ResumePreview = useMemo(() => {
    return (
      <Component
        fontScale={fontScale}
        isNeedPaging={true}
        resume={{
          content,
          customization,
          personalDetails,
        }}
        onReady={(pageNum) => {
          pageNumRef.current = pageNum;
          (ref.current as any).style.height = `${
            (pageNum * a4Height + (pageNum - 1) * 10) * scaleRef.current
          }px`;
        }}
        onChange={onChange}
      />
    );
  }, [content, customization, personalDetails, fontScale]);
  return (
    <div ref={ref} style={{ margin: "0 auto", overflow: "hidden" }}>
      <div
        ref={ref2}
        style={{ transform: `scale(${scale})`, transformOrigin: "left top" }}
      >
        {show ? ResumePreview : null}
      </div>
    </div>
  );
};

export default Index;
